<template>
  <el-row>
    <el-col :span="4" :offset="2">
      <el-upload
        ref="updload_avatar"
        action=""
        list-type="picture-card"
        class="avatar-uploader"
        :auto-upload="false"
        :limit="1"
        :on-change="getFile"
      >
        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
        <i v-else class="el-icon-plus avatar-uploader-icon" />
      </el-upload>
      <div class="box">
        <h1>base64图片上传</h1>
        <img
          v-if="userInfo.accountImg"
          ref="img"
          class="avatar-img"
          :src="userInfo.accountImg"
        />
      </div>
    </el-col>
    <el-col :span="8" :offset="2">
      <el-button type="success" @click="submit">保存</el-button>
      <el-button type="info" @click="clean">重置</el-button>
    </el-col>
  </el-row>
</template>

<script>
import { mapState } from "vuex";
import { getUserAvatar } from "../api/data";
export default {
  name: "imageUpload",
  data() {
    return {
      userInfo: {},
      imageUrl: "",
    };
  },
  methods: {
    submit() {
      let Authorization = this.$store.state.user.token;
      let avatar = this.userInfo.accountImg;
      let params = [{ avatar }, Authorization];
      getUserAvatar(params).then(({ data: res }) => {
        if (res.status == 0) {
          this.$message({
            message: "上传成功",
            type: "success",
          });
        } else {
          this.$message({
            message: "上传失败",
            type: "warning",
          });
        }
      });
    },
    clean() {},
    // 用于获取base64字符
    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        let imgResult = "";
        reader.readAsDataURL(file);
        reader.onload = function () {
          imgResult = reader.result;
        };
        reader.onerror = function (error) {
          reject(error);
        };
        reader.onloadend = function () {
          resolve(imgResult);
        };
      });
    },
    // 文件校验
    verifyFile(file) {
      return new Promise((resolve, reject) => {
        const isJPG = file.type === "image/png";
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          reject("上传头像图片只能是 [jpg, png, gif] 格式!");
        }
        if (!isLt2M) {
          reject("上传头像图片大小不能超过 2MB!");
        }
        resolve(isJPG && isLt2M);
      });
    },
    // upload组件触发改变的事件
    getFile(file, fileList) {
      // 清除上一次选择的文件 避免后面不在触发此事件
      this.$refs["updload_avatar"].clearFiles();

      // 文件格式及大小校验、获取base64
      this.verifyFile(file.raw)
        .then((resp) => {
          return this.getBase64(file.raw);
        })
        .then((resp) => {
          // 这里强调一下为什么是使用这种方式而不是使用
          // this.userInfo.accountImg = resp
          // 因为vue 数据监测不到对象深处的数据更改，所以需要使用$set通知一下vue
          // 不这样写会导致页面中的图片展示不生效
          this.$set(this.userInfo, "accountImg", resp);
        })
        .catch((err) => {
          this.$message(err);
        });
    },
  },
  computed: {
    ...mapState({
      userToken: (state) => state.user.token,
    }),
  },
};
</script>

<style lang="less" scoped>
.avatar-img {
  width: 200px;
  height: 200px;
}
.box {
  margin-top: 30px;
}
</style>